﻿using System;
using System.Collections.Generic;
using System.Text;
using ExpressionUtil.Node.Common;
using ExpressionUtil.Common;
using ExpressionUtil.Parser;
using System.Diagnostics;
using System.Runtime.Serialization;

namespace ExpressionUtil.Node
{
    /// <summary>
    /// 取整运算节点
    /// </summary>
    [Serializable]
    internal class TruncFunctionNode : Common.FunctionNode, ISerializable
    {
        /// <summary>
        /// 默认构造函数
        /// </summary>
        public TruncFunctionNode()
            : base()
        {
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="info">要填充数据的 System.Runtime.Serialization.SerializationInfo</param>
        /// <param name="context">此序列化的目标</param>
        public TruncFunctionNode(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
        }

        /// <summary>
        /// 执行节点运算
        /// </summary>
        /// <param name="context">执行参数</param>
        /// <returns>执行结果的类型</returns>
        public override ExecuteRunTimeType Execute(ExecuteContext context)
        {
            ExecuteRunTimeType type = this.Parameters[0].Execute(context);
            CheckHelper.IsDecimalType(type, "Trunc function parameter must be decimal type.");
            decimal num = context.GlobalTempNum;
            context.GlobalTempNum = Math.Truncate(num);
            return ExecuteRunTimeType.Decimal;
        }

        /// <summary>
        /// 创建树节点
        /// </summary>
        /// <param name="context">解析参数</param>
        public static void CreateTruncFunctionNode(ParseContext context)
        {
            if (context.PostfixStack.Count < 1)
            {
                throw new FormatException("Trunc function missing operand.");
            }
            TruncFunctionNode node = new TruncFunctionNode();
            node.Parameters.Add(context.PostfixStack.Pop());
            context.PostfixStack.Push(node);
        }

#if DEBUG
        protected override void DumpCore()
        {
            Debug.WriteLine("TruncFunctionNode,children:");
            this.Parameters[0].DumpNode();
        }
#endif
    }
}
